package model

import (
	"errors"
	"golang.org/x/crypto/bcrypt"
)

type User struct {
	UserId       int    `db:"user_id"`
	UserName     string `db:"user_name"`
	NickName     string `db:"nick_name"`
	PasswordHash []byte `db:"password_hash"`
	Mobile       string `db:"mobile"`
	Email        string `db:"email"`
	Weixin       string `db:"weixin"`
	QQ           string `db:"qq"`
	CreatedAt    int64  `db:"created_at"`
	DeletedAt    int64  `db:"deleted_at"`
}

func (u *User) SetPassword(password string) error {
	hash, err := HashPassword(password)
	if err != nil {
		return err
	}
	u.PasswordHash = hash
	return nil
}
func (u *User) CheckPassword(password string) error {
	if u.PasswordHash != nil && len(u.PasswordHash) == 0 {
		return errors.New("password not set")
	}
	return bcrypt.CompareHashAndPassword(u.PasswordHash, []byte(password))
}
func HashPassword(password string) ([]byte, error) {
	return bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
}
